<template>
  <div class="address-page">
    <!-- 顶部导航 -->
    <div class="nav-header">
      <button class="back-button" @click="goBack">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <path d="m15 18-6-6 6-6" />
        </svg>
      </button>
      <h2>选择收货地址</h2>
    </div>

    <!-- 地址列表 -->
    <div class="address-list">
      <div
        v-for="addr in addresses"
        :key="addr.addressesId"
        class="address-item"
        :class="{ 'selected': selectedAddressId === addr.addressesId }"
        @click="selectAddress(addr)"
      >
        <div class="address-content">
          <div class="contact-info">
            <span class="name">{{ addr.recipientName }}</span>
            <span class="phone">{{ addr.phone }}</span>
          </div>
          <div class="address-detail">{{ addr.address }}</div>
        </div>
        <div class="actions">
          <button class="edit-btn" @click.stop="showEditForm(addr)">编辑</button>
          <button class="delete-btn" @click.stop="deleteAddress(addr)">删除</button>
        </div>
      </div>
    </div>

    <!-- 底部添加按钮 -->
    <div class="add-address">
      <button class="add-btn" @click="addNewAddress">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <line x1="12" y1="5" x2="12" y2="19"></line>
          <line x1="5" y1="12" x2="19" y2="12"></line>
        </svg>
        新增收货地址
      </button>
    </div>

    <!-- 修改弹出层部分 -->
    <van-popup v-model:show="showAddressForm" position="bottom" round>
      <van-address-edit
        :area-list="areaList"
        :address-info="currentAddress"
        :show-delete="isEdit"
        :area-columns-placeholder="['请选择省份', '请选择城市', '请选择区县']"
        @save="saveAddress"
        @delete="deleteAddress"
      />
    </van-popup>

    <!-- Confirmation Modal -->
    <div v-if="showDeleteConfirm" class="confirmation-modal">
      <div class="modal-content">
        <h3>确认删除</h3>
        <p>您确定要删除这个地址吗？</p>
        <div class="modal-buttons">
          <button class="btn-confirm" @click="confirmDelete">确定</button>
          <button class="btn-cancel" @click="cancelDelete">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { addAddress, getAddressList, editAddress as updateAddress, deleteAddress as removeAddress } from './api/index.js'
import { showToast } from 'vant'
import 'vant/lib/index.css'


const areaList = {
  // 省级数据（34 个省级行政单位）
  province_list: {
    500000: '重庆市',
    110000: '北京市',
    120000: '天津市',
    130000: '河北省',
    140000: '山西省',
    150000: '内蒙古自治区',
    210000: '辽宁省',
    220000: '吉林省',
    230000: '黑龙江省',
    310000: '上海市',
    320000: '江苏省',
    330000: '浙江省',
    340000: '安徽省',
    350000: '福建省',
    360000: '江西省',
    370000: '山东省',
    410000: '河南省',
    420000: '湖北省',
    430000: '湖南省',
    440000: '广东省',
    450000: '广西壮族自治区',
    460000: '海南省',
    510000: '四川省',
    520000: '贵州省',
    530000: '云南省',
    540000: '西藏自治区',
    610000: '陕西省',
    620000: '甘肃省',
    630000: '青海省',
    640000: '宁夏回族自治区',
    650000: '新疆维吾尔自治区',
    710000: '台湾省', // 注：实际由中华民国管辖，PRC 声称主权
    810000: '香港特别行政区',
    820000: '澳门特别行政区'
  },

  // 市级数据（部分示例）
  city_list: {
    // 北京市（直辖市，市级和省级代码相同）
    110100: '北京市',
    // 天津市（直辖市）
    120100: '天津市',
    // 重庆市（直辖市）
    500100: '重庆市',
    500200: '重庆市郊县', // 重庆市部分区县未细分时使用
    // 广东省（部分地级市）
    440100: '广州市',
    440300: '深圳市',
    440400: '珠海市',
    440500: '汕头市',
    441300: '惠州市',
    441900: '东莞市',
    442000: '中山市'
    // 其他省份的地级市可以继续添加，例如：
    // 130100: '石家庄市', // 河北省
    // 320100: '南京市', // 江苏省
  },

  // 县级数据（部分示例）
  county_list: {
    // 北京市
    110101: '东城区',
    110102: '西城区',
    110105: '朝阳区',
    110106: '丰台区',
    110107: '石景山区',
    110108: '海淀区',
    110109: '门头沟区',
    110111: '房山区',
    110112: '通州区',
    110113: '顺义区',
    110114: '昌平区',
    110115: '大兴区',
    110116: '怀柔区',
    110117: '平谷区',
    110118: '密云区',
    110119: '延庆区',
    // 天津市
    120101: '和平区',
    120102: '河东区',
    120103: '河西区',
    120104: '南开区',
    120105: '河北区',
    120106: '红桥区',
    120110: '东丽区',
    120111: '西青区',
    120112: '津南区',
    120113: '北辰区',
    120114: '武清区',
    120115: '宝坻区',
    120116: '滨海新区',
    120117: '宁河区',
    120118: '静海区',
    120119: '蓟州区',
    // 重庆市（部分区县）
    500101: '万州区',
    500102: '涪陵区',
    500103: '渝中区',
    500104: '大渡口区',
    500105: '江北区',
    500106: '沙坪坝区',
    500107: '九龙坡区',
    500108: '南岸区',
    500109: '北碚区',
    500110: '綦江区',
    500111: '大足区',
    500112: '渝北区',
    500113: '巴南区',
    500114: '黔江区',
    500115: '长寿区',
    // 广东省广州市
    440103: '荔湾区',
    440104: '越秀区',
    440105: '海珠区',
    440106: '天河区',
    440111: '白云区',
    440112: '黄埔区',
    440113: '番禺区',
    440114: '花都区',
    440115: '南沙区',
    440117: '从化区',
    440118: '增城区',
    // 广东省深圳市
    440303: '罗湖区',
    440304: '福田区',
    440305: '南山区',
    440306: '宝安区',
    440307: '龙岗区',
    440308: '盐田区',
    440309: '龙华区',
    440310: '坪山区',
    440311: '光明区'
    // 其他区县可以继续添加
  }
};
// 当前编辑的地址信息
const currentAddress = ref({})

// 保持原有的状态管理
const router = useRouter()
const route = useRoute()
const addresses = ref([])
const selectedAddressId = ref(null)
const showAddressForm = ref(false)
const isEdit = ref(false)

const showDeleteConfirm = ref(false)
const addressToDelete = ref(null)

const goBack = () => {
  router.go(-1)
}

const selectAddress = (address) => {
  selectedAddressId.value = address.addressesId
console.log(address.addressesId)
  // 将选中的地址信息传回订单页面
  if (route.query.orderInfo && route.query.from !== 'cart') {
    console.log(route.query.orderInfo,route.query.from)
  router.push({
    path: '/order',
    query: {
      orderInfo: route.query.orderInfo, // 保持原有订单信息
      selectedAddress: JSON.stringify({
        id: address.addressesId,
        name: address.recipientName,
        phone: address.phone,
        fullAddress: address.address
      })
    }
  })
}else{
  router.push({
    path: '/order/cart',
    query: {
      orderInfo: route.query.orderInfo, // 保持原有订单信息
      selectedAddress: JSON.stringify({
        id: address.addressesId,
        name: address.recipientName,
        phone: address.phone,
        fullAddress: address.address
      })
    }
  })
}
}

const showEditForm = (address) => {
  isEdit.value = true
  currentAddress.value = {
    id: address.addressesId,
    name: address.recipientName,
    tel: address.phone,
    addressDetail: address.address.split(' ')[1] || '',
    province: address.address.split(' ')[0] || ''
  }
  showAddressForm.value = true
}

const deleteAddress = async (address) => {
  addressToDelete.value = address
  showDeleteConfirm.value = true
}

const confirmDelete = async () => {
  try {
    console.log('Deleting address:', addressToDelete.value)
    await removeAddress(addressToDelete.value.addressesId)
    const listRes = await getAddressList()
    addresses.value = listRes.data.data
    closeForm()
  } catch (error) {
    console.error('Failed to delete address:', error)
  } finally {
    showDeleteConfirm.value = false
    addressToDelete.value = null
  }
}

const cancelDelete = () => {
  showDeleteConfirm.value = false
  addressToDelete.value = null
}

const addNewAddress = () => {
  isEdit.value = false
  currentAddress.value = {}
  showAddressForm.value = true
}

// 关闭表单
const closeForm = () => {
  showAddressForm.value = false
}

// 保存地址
const saveAddress = async (content) => {
  try {
    const addressData = {
      recipientName: content.name,
      phone: content.tel,
      address: `${content.province} ${content.addressDetail}`
    }

    if (isEdit.value) {
      await updateAddress(
        currentAddress.value.id,
        addressData.recipientName,
        addressData.phone,
        addressData.address
      )
    } else {
      await addAddress(
        addressData.recipientName,
        addressData.phone,
        addressData.address
      )
    }

    const listRes = await getAddressList()
    addresses.value = listRes.data.data
    showAddressForm.value = false
    showToast('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    showToast('保存失败')
  }
}

onMounted(async () => {
  const res = await getAddressList()
  addresses.value = res.data.data
})
</script>

<style lang="scss" scoped>
.address-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 60px;
}

.nav-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 100;

  .back-button {
    background: none;
    border: none;
    padding: 8px;
    margin-left: -8px;
  }

  h2 {
    flex: 1;
    text-align: center;
    margin: 0;
    font-size: 16px;
  }
}

.address-list {
  margin-top: 44px;
  padding: 12px;

  .address-item {
    background-color: white;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 12px;
    border: 1px solid transparent;

    &.selected {
      border-color: #ff3b30;
    }

    .address-content {
      .contact-info {
        margin-bottom: 8px;

        .name {
          font-size: 16px;
          font-weight: bold;
          margin-right: 12px;
        }

        .phone {
          color: #666;
        }
      }

      .address-detail {
        color: #333;
        font-size: 14px;
      }
    }

    .actions {
      margin-top: 12px;
      display: flex;
      justify-content: flex-end;
      gap: 12px;

      button {
        background: none;
        border: none;
        font-size: 14px;
        padding: 4px 8px;

        &.edit-btn {
          color: #666;
        }

        &.delete-btn {
          color: #ff3b30;
        }
      }
    }
  }
}

.add-address {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px 16px;
  background-color: white;

  .add-btn {
    width: 100%;
    height: 44px;
    background-color: #ff3b30;
    color: white;
    border: none;
    border-radius: 22px;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;

    &:active {
      opacity: 0.9;
    }
  }
}

// 添加 Vant 组件相关样式覆盖
:deep(.van-address-edit) {
  padding: 16px;

  // 修改保存按钮颜色
  .van-button--danger {
    background-color: #ff3b30;
    border-color: #ff3b30;
  }

  // 修改保存按钮激活状态颜色
  .van-button--danger:active {
    background-color: #e03444;
    border-color: #e03444;
  }

  // 如果需要修改其他按钮样式
  .van-button {
    background-color: #fb4033;
    border-color: #fb4033;
    border-radius: 14px;
  }
}

:deep(.van-popup) {
  max-height: 80vh;
}

.confirmation-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  width: 80%;
  max-width: 400px;
  text-align: center;
}

.modal-content h3 {
  margin-top: 0;
  color: #333;
  font-size: 18px;
}

.modal-content p {
  margin: 15px 0;
  color: #666;
}

.modal-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.btn-confirm, .btn-cancel {
  padding: 8px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn-confirm {
  background-color: #ff4757;
  color: white;
}

.btn-confirm:hover {
  background-color: #e03444;
}

.btn-cancel {
  background-color: #f1f2f6;
  color: #333;
}

.btn-cancel:hover {
  background-color: #dfe4ea;
}
</style>
